package handler

import (
	"context"
	"filestore-rebuild/util/jwtUtil"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

// JWT JWT验证中间价
func JWT() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.GetHeader("Token")
		if token == "" {
			ctx.JSON(http.StatusOK, gin.H{
				"code": http.StatusUnauthorized,
				"msg":  "没有携带token",
				"data": "",
			})
			ctx.Abort()
			return
		} else {
			claims, err := jwtUtil.ParseToken(token)
			if err != nil {
				ctx.JSON(http.StatusOK, gin.H{
					"code": http.StatusUnauthorized,
					"msg":  "token验证失败",
					"data": "",
				})
				ctx.Abort()
				return
			} else if time.Now().Unix() > claims.StandardClaims.ExpiresAt {
				ctx.JSON(http.StatusOK, gin.H{
					"code": http.StatusUnauthorized,
					"msg":  "token已过期",
					"data": "",
				})
				ctx.Abort()
				return
			}
			c := context.WithValue(ctx.Request.Context(), "username", claims.UserID)
			ctx.Request = ctx.Request.WithContext(c)
		}
	}
}
